
/**
 * EXIT INTENT SCROLL MAT - VERSION 5.0
 *
 * - Shows only ONCE per page load
 * - Resets when page is refreshed
 * - No cookies or sessionStorage
 * - Different offer URL per WordPress post
 * - External HTTPS pages supported
 * - Full-screen slide-in from the left
 * - Bright yellow circular close button
 */

// Run on the front end.
add_action('wp_footer', function () {

    // ============================================
    // CONFIGURATION - EDIT THIS SECTION ONLY
    // ============================================

    // LEFT = WordPress blog post ID
    // RIGHT = Opt-in page URL to display

    $exit_pages = [
        123 => 'https://yourwebsite.com/offer-one/',
        456 => 'https://yourwebsite.com/offer-two/',
        789 => 'https://anotherwebsite.com/offer-three/',
    ];

    // ============================================
    // END CONFIGURATION
    // ============================================

    // Only run on regular WordPress blog posts.
    if (!is_singular('post')) {
        return;
    }

    $post_id = get_queried_object_id();

    // Only display on configured posts.
    if (!isset($exit_pages[$post_id])) {
        return;
    }

    $offer_url = esc_url_raw($exit_pages[$post_id]);

    // Validate HTTPS destination.
    if (
        wp_parse_url($offer_url, PHP_URL_SCHEME) !== 'https' ||
        !wp_parse_url($offer_url, PHP_URL_HOST)
    ) {
        return;
    }

    // Manual test:
    // Add ?exitmat_test=1 to the blog post URL.
    $test_mode = isset($_GET['exitmat_test'])
        && $_GET['exitmat_test'] === '1';

    ?>

    <style>
        /* FULL-SCREEN SCROLL MAT */

        #ei-scrollmat {
            position: fixed !important;
            inset: 0 !important;
            width: 100vw !important;
            height: 100vh !important;
            height: 100dvh !important;
            margin: 0 !important;
            padding: 0 !important;
            z-index: 2147483647 !important;

            background: #ffffff !important;

            transform: translate3d(-101%, 0, 0);
            visibility: hidden;
            pointer-events: none;

            transition:
                transform .65s cubic-bezier(.22,1,.36,1),
                visibility 0s linear .65s;
        }

        /* SCROLL MAT ACTIVE */

        #ei-scrollmat.ei-open {
            transform: translate3d(0,0,0);
            visibility: visible;
            pointer-events: auto;

            transition:
                transform .65s cubic-bezier(.22,1,.36,1),
                visibility 0s;
        }

        /* EMBEDDED OPT-IN PAGE */

        #ei-scrollmat iframe {
            display: block !important;
            width: 100% !important;
            height: 100% !important;
            border: 0 !important;
            margin: 0 !important;
            padding: 0 !important;
            background: #ffffff !important;
        }

        /* YELLOW CIRCULAR CLOSE BUTTON */

        #ei-close {
            position: absolute !important;
            top: 18px !important;
            right: 22px !important;
            left: auto !important;
            z-index: 2147483647 !important;

            width: 48px !important;
            height: 48px !important;
            min-width: 48px !important;
            min-height: 48px !important;

            display: flex !important;
            align-items: center !important;
            justify-content: center !important;

            background: #FFEB00 !important;
            color: #000000 !important;

            border: 2px solid #000000 !important;
            border-radius: 50% !important;

            font: bold 30px/1 Arial,sans-serif !important;
            cursor: pointer !important;
            padding: 0 !important;

            box-shadow: 0 4px 15px rgba(0,0,0,.25);

            transition:
                background .2s ease,
                color .2s ease,
                transform .2s ease,
                box-shadow .2s ease !important;
        }

        /* CLOSE BUTTON HOVER */

        #ei-close:hover {
            background: #000000 !important;
            color: #FFEB00 !important;
            transform: scale(1.12);
            box-shadow: 0 6px 20px rgba(0,0,0,.35);
        }

        #ei-close:focus-visible {
            outline: 3px solid #000 !important;
            outline-offset: 4px;
        }

        /* MANUAL TEST BUTTON */

        #ei-test-button {
            position: fixed !important;
            bottom: 20px !important;
            right: 20px !important;
            z-index: 2147483646 !important;

            padding: 12px 18px !important;
            background: #FFEB00 !important;
            color: #000000 !important;

            border: 2px solid #000000 !important;
            border-radius: 8px !important;

            font: bold 14px Arial,sans-serif !important;
            cursor: pointer !important;
        }

        /* MOBILE DISPLAY ADJUSTMENTS */

        @media (max-width: 600px) {
            #ei-close {
                top: 12px !important;
                right: 12px !important;
                width: 44px !important;
                height: 44px !important;
                min-width: 44px !important;
                min-height: 44px !important;
            }
        }

        /* REDUCED MOTION */

        @media (prefers-reduced-motion: reduce) {
            #ei-scrollmat,
            #ei-close {
                transition: none !important;
            }
        }
    </style>

    <!-- EXIT INTENT SCROLL MAT -->

    <div
        id="ei-scrollmat"
        role="dialog"
        aria-modal="true"
        aria-label="Special offer"
        aria-hidden="true"
        inert
    >
        <button
            type="button"
            id="ei-close"
            aria-label="Close special offer"
        >&times;</button>

        <iframe
            id="ei-frame"
            title="Special offer"
            data-url="<?php echo esc_url($offer_url); ?>"
            referrerpolicy="strict-origin-when-cross-origin"
        ></iframe>
    </div>

    <?php if ($test_mode) : ?>
        <button id="ei-test-button" type="button">
            TEST SCROLL MAT
        </button>
    <?php endif; ?>

    <script>
    (function () {
        'use strict';

        function initialize() {

            const mat = document.getElementById('ei-scrollmat');
            const closeBtn = document.getElementById('ei-close');
            const frame = document.getElementById('ei-frame');
            const testBtn = document.getElementById('ei-test-button');

            if (!mat || !closeBtn || !frame) return;

            // ======================================
            // IMPORTANT: ONCE PER PAGE LOAD
            // ======================================

            let isOpen = false;
            let hasBeenShown = false;

            let previousFocus = null;
            let savedOverflow = '';

            // Move overlay under body.
            if (mat.parentElement !== document.body) {
                document.body.appendChild(mat);
            }

            function showMat() {

                // Never reopen after first appearance.
                if (isOpen || hasBeenShown) {
                    return;
                }

                isOpen = true;
                hasBeenShown = true;

                previousFocus = document.activeElement;
                savedOverflow = document.body.style.overflow;

                // Load opt-in URL.
                if (!frame.getAttribute('src')) {
                    frame.src = frame.dataset.url;
                }

                mat.removeAttribute('inert');
                mat.setAttribute('aria-hidden', 'false');
                mat.classList.add('ei-open');

                document.body.style.overflow = 'hidden';

                closeBtn.focus();
            }

            function hideMat() {

                if (!isOpen) return;

                isOpen = false;

                mat.classList.remove('ei-open');

                document.body.style.overflow = savedOverflow;

                // Restore keyboard focus before hiding.
                if (
                    previousFocus &&
                    typeof previousFocus.focus === 'function'
                ) {
                    previousFocus.focus();
                } else {
                    closeBtn.blur();
                }

                mat.setAttribute('inert', '');
                mat.setAttribute('aria-hidden', 'true');

                // hasBeenShown remains TRUE.
                // Refreshing the page resets it.
            }

            // ======================================
            // EXIT INTENT DETECTION
            // ======================================

            function detectExit(e) {

                if (isOpen || hasBeenShown) return;

                // Ignore movement between elements.
                if (e.relatedTarget) return;

                // Mouse leaves near top of browser.
                if (e.clientY <= 30) {
                    showMat();
                }
            }

            document.addEventListener(
                'mouseout',
                detectExit
            );

            document.documentElement.addEventListener(
                'mouseleave',
                function(e) {

                    if (
                        !isOpen &&
                        !hasBeenShown &&
                        e.clientY <= 30
                    ) {
                        showMat();
                    }
                }
            );

            // ======================================
            // MANUAL TEST BUTTON
            // ======================================

            if (testBtn) {
                testBtn.addEventListener('click', showMat);
            }

            // ======================================
            // CLOSE BUTTON
            // ======================================

            closeBtn.addEventListener('click', hideMat);

            // ESCAPE KEY

            document.addEventListener('keydown', function(e) {

                if (
                    e.key === 'Escape' &&
                    isOpen
                ) {
                    hideMat();
                }
            });
        }

        if (document.readyState === 'loading') {
            document.addEventListener(
                'DOMContentLoaded',
                initialize
            );
        } else {
            initialize();
        }

    })();
    </script>

    <?php

}, 100);
